/*
 * @Author: sunli
 * @Date: 2024-02-21 10:35:21
 * @LastEditors: sunli
 * @LastEditTime: 2024-02-21 16:21:26
 * @FilePath: /debug-server/router/project.js
 * @Description: 
 */
let express = require('express')
let router = express()
let mongoose = require('mongoose')
let projectModel = mongoose.model('project')

router.post('/add', async (req, res) => {
  const body = req.body

  // 完整性校验
  if (!body.name || !body.type || !body.projectMobile || !body.projectEmail) {
    return res.send({code: 0,message: '未完善信息'})
  }

  const data = new projectModel({
    owner: body.owner,
    KEY: `${new Date().getTime()}-${body.name}`,
    name: body.name,
    type: body.type,
    language: 'javascript',
    projectMobile: body.projectMobile,
    projectEmail: body.projectEmail,
    reportMobile: true,
    reportEmail: true
  })

  data.save()
    .then(async () => {
      res.send({
        code: 1,
        message: '项目创建成功',
      })
    })
    .catch(error => {
      res.send({
        code: 0,
        message: '项目创建失败'
      })
    })
})

router.post('/list', async (req, res) => {
  const body = req.body

  const result = await projectModel.find({ owner: body.userName })

  res.send({
    code: 1,
    message: '查询成功',
    resObject: result || []
  })
})
router.post('/queryByKEY', async (req, res) => {
  const body = req.body

  const result = await projectModel.findOne({ KEY: body.KEY })

  res.send({
    code: 1,
    message: '查询成功',
    resObject: result
  })
})

router.post('/update', async (req, res) => {
  const body = req.body
  projectModel.updateOne({ KEY: body.KEY },
    {
      reportMobile: body.reportMobile,
      reportEmail: body.reportEmail,
      projectMobile: body.projectMobile,
      projectEmail: body.projectEmail
    }, (err) => {
    if (err) {
      res.send({
        code: 0,
        message: '更新失败'
      })
    } else {
      res.send({
        code: 1,
        message: '更新成功'
      })
    }
  })
})

router.post('/detele', async (req, res) => {
  const body = req.body

  projectModel.deleteOne({ KEY: body.KEY }, (err) => {
    if (err) {
      res.send({
        code: 0,
        message: '删除失败'
      })
    } else {
      res.send({
        code: 1,
        message: '删除成功'
      })
    }
  })
})

module.exports = router
